import Dexie from "dexie";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const IDBExportImport = require("indexeddb-export-import");
const db = new Dexie("EWG_DB");

export const exportArchive = () => {
  db.open()
    .then(function() {
      const idbDatabase = db.backendDB(); // get native IDBDatabase object from Dexie wrapper
      // export to JSON, clear database, and import from JSON
      IDBExportImport.exportToJsonString(idbDatabase, function(
        err: any,
        jsonString: string
      ) {
        if (err) {
          console.error(err);
        } else {
          // Convert JSON string to BLOB.
          // [数据库明文存档, localStorage存档]
          const json = [JSON.stringify(jsonString)];
          const blob1 = new Blob(json, {
            type: "text/plain;charset=utf-8"
          });
          const url = window.URL || window.webkitURL;
          const link = url.createObjectURL(blob1);
          const a = document.createElement("a");
          a.download = "EWG.bak";
          a.href = link;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
        }
      });
    })
    .catch(function(e) {
      console.error("Could not connect. " + e);
    });
};

export const importArchive = () => {
  const jsonString = "";
  const idbDatabase = db.backendDB(); // get native IDBDatabase object from Dexie wrapper
  IDBExportImport.clearDatabase(idbDatabase, function(err: any) {
    if (!err) {
      // cleared data successfully
      IDBExportImport.importFromJsonString(idbDatabase, jsonString, function(
        err: any
      ) {
        if (!err) {
          console.log("Imported data successfully");
        }
      });
    }
  });
};
